package edu.gmu.projects.fireresponder.gui;

import java.util.Calendar;
import java.util.Iterator;
import java.util.Map;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.preference.Preference.OnPreferenceChangeListener;
import android.util.Log;
import edu.gmu.projects.fireresponder.comm.UDPBroadcast;
import edu.gmu.projects.fireresponder.environment.Asset;
import edu.gmu.projects.fireresponder.environment.Building;
import edu.gmu.projects.fireresponder.environment.Asset.AssetStatus;
import edu.gmu.projects.fireresponder.fusionengine.FusionEngine;
import edu.gmu.projects.fireresponder.missionplanner.SituationEnvironment;
import edu.gmu.projects.fireresponder.relevancyengine.RelevanceEngine;
import edu.gmu.projects.fireresponder.relevancyengine.RelevanceEngineService;
import edu.gmu.projects.fireresponder.xml.alerts.AlertGenerator;

public class MissionPlanPreferenceActivity extends PreferenceActivity {
	private static final String MISSION_PLAN_ACTIVITY = "edu.gmu.projects.fireresponder.gui.MissionPlanPreferenceActivity";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		PreferenceManager manager = MissionPlanPreferenceActivity.this
				.getPreferenceManager();

		manager.setSharedPreferencesName(MISSION_PLAN_ACTIVITY);
		manager.getSharedPreferences().edit().clear().commit();

		bindService(new Intent(MissionPlanPreferenceActivity.this,
				RelevanceEngineService.class), relevanceConnection,
				BIND_AUTO_CREATE);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		unbindService(relevanceConnection);
	}

	private RelevanceEngineService relevanceService;

	private ServiceConnection relevanceConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName name, IBinder service) {
			relevanceService = ((RelevanceEngineService.LocalBinder) service)
					.getService();

			Map<String, Asset> plan = relevanceService.getRelevanceEngine()
					.getMissionPlan();

			Iterator<String> iter = plan.keySet().iterator();

			PreferenceManager manager = MissionPlanPreferenceActivity.this
					.getPreferenceManager();
			PreferenceScreen screen = MissionPlanPreferenceActivity.this
					.getPreferenceScreen();
			screen = manager.createPreferenceScreen(getApplicationContext());

			while (iter.hasNext()) {
				String key = iter.next();
				Asset asset = plan.get(key);
				double fireProb = asset.getProbabilityOfFire();
				double peopleProb = asset.getProbabilityOfPresence();
				double relevance = asset.getRelevanceValue();

				String fireProbStr = String.format("Fire prob: %s, ",
						FusionEngine.getProbabilityCategoryText(fireProb));
				String peopleProbStr = String.format("People prob: %s, ",
						FusionEngine.getProbabilityCategoryText(peopleProb));
				String relevanceStr = String.format("Misison Relevance: %s",
						RelevanceEngine.getRelevanceScaleText(relevance));
				String summary = fireProbStr + "\n" + peopleProbStr + "\n"
						+ relevanceStr;

				Preference pref = null;
				boolean isComplete = asset.getStatus() == AssetStatus.COMPLETE;

				pref = new CheckBoxPreference(getApplicationContext());

				((CheckBoxPreference) pref).setChecked(isComplete);

				AssetCompleteChangeListener listener = new AssetCompleteChangeListener(
						asset);

				pref.setOnPreferenceChangeListener(listener);

				if (asset instanceof Building) {
					pref.setTitle(asset.getId());
				} else {
					pref.setTitle(asset.getClass().getSimpleName() + " "
							+ asset.getId());
				}

				pref.setEnabled(!isComplete);
				pref.setSummary(summary);
				pref.setKey(key);

				screen.addItemFromInflater(pref);
			}

			MissionPlanPreferenceActivity.this.setPreferenceScreen(screen);

			Log.i("MissionPlanListActivity",
					"Connected to RelevanceEngineService");
		}

		public void onServiceDisconnected(ComponentName name) {
			relevanceService = null;

			Log.i("MissionPlanListActivity",
					"Disconnected from RelevanceEngineService");
		}
	};

	public class AssetCompleteChangeListener implements
			OnPreferenceChangeListener {
		Asset asset;

		public AssetCompleteChangeListener(Asset asset) {
			this.asset = asset;
		}

		public boolean onPreferenceChange(Preference preference, Object newValue) {
			Boolean checked = (Boolean) newValue;

			if (checked) {
				preference.setEnabled(false);

				if (asset instanceof Building) {
					sendBuildingCheckedAlert(asset);
				}

				relevanceService.getRelevanceEngine().onResponderSetCompleted(
						asset);
			}

			return true;
		}

		private void sendBuildingCheckedAlert(Asset asset) {
			Calendar cal = Calendar.getInstance();

			String frName = SituationEnvironment.getSituationEnvironment(
					MissionPlanPreferenceActivity.this).getSelf().getId();

			double lat = asset.getCenter().getLatitude();
			double lng = asset.getCenter().getLongitude();

			String msg = new AlertGenerator()
					.generateResponderBuildingClearedAlert(frName, asset
							.getId(), cal, lat, lng, "");

			if (msg != null) {
				UDPBroadcast.getUDPBroadcast().send(msg);
			}
		}
	}
}